<template>
  <div class="subcontract-registration-manage" v-loading="listLoading" element-loading-text="隐患库初始化...">
    <div class="model-title-css">
      <div>{{ title }}</div>
      <div class="flex-center g-flex flex-right">
        <el-select style="margin: 0; margin-right: 15px" class="select" size="small" v-model="search.projectId" v-on:change="getSectionByProjectId()" value-key="id" filterable placeholder="选择项目">
          <el-option v-for="item in projectTree" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-input style="padding-right: 15px" placeholder="查找类别名称" v-model="filterText">
        </el-input>
        <div class="left-tree-box WholeScroll">
          <el-tree class="imageProgressSummary-tree" :data="leftList" :props="defaultProps" ref='treeData' node-key="id" :filter-node-method="filterNode" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
        </div>
        <el-button class="bottom-button" type="primary" size="small" @click="showTreeEditDialog">
          隐患类别管理
        </el-button>
      </div>
      <div class="right-box">
        <div class="operate_wrap flex">
          <div class="flex-center">
            <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '新增')"><i class="iconfont icon-icon_add"></i> 新增
            </el-button>
            <el-button type="primary" size="small" class="delete buildButtonStyle" round @click="deleteList"><i class="iconfont icon-icon_cancel"></i> 删除
            </el-button>

            <!-- <el-upload class="upload-demo fill span18" action="" :before-upload="submitImportExcel">
              <el-button id="excel-import-button" class="delete" style="width: 110px;margin: 0 10px" size="small" v-permission="permission.add"><i class="iconfont icon-icon_zp"></i> 导入excel
              </el-button>
            </el-upload> -->

            <!--            <el-button class="delete" size="small" style="width: 110px;" @click="templateDownload"  v-permission="permission.add">-->
            <!--              <i class="iconfont icon-daochu"></i> 模板下载-->
            <!--            </el-button>-->
          </div>
          <div class="flex-left">
            <el-input v-model="search.checkContent" clearable size="mini" placeholder="搜索排查内容" style="margin-left: 364px;width: 200px;"></el-input>
            <el-button class="search" size="small" @click="getList()">

              <i class="iconfont icon-sousuo"></i> 搜索
            </el-button>
          </div>
        </div>
        <div class="list_wrap">
          <el-table class="table-three-blue" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="xh" align="center" label="序号" width="60">
              <template slot-scope="scope">
                {{ scope.$index + search.pageNo * search.pageSize + 1 }}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip prop="checkContent" label="排查内容">
              <template slot-scope="scope">
                <div>{{scope.row.checkContent}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="整改要求">
              <template slot-scope="scope">
                <div>{{scope.row.rectificationRequirements}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="事故隐患" width="180">
              <template slot-scope="scope">
                <div>
                  {{scope.row.accidentPotential | optionFilterByRow({ options: accidentPotentialArr, labelKey: 'name', valueKey: 'id' })}}
                </div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="整改时限（天）" width="230">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.rectificationTimeLimit}}</div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float: right; margin-top: 30px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
    <tree-edit-dialog :postDetail="treeEditDialogData" @reloadList="getLeftTreeNew()"></tree-edit-dialog>

  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject
} from '@/utils/publicFun'

import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import dailyprogress from '@/api/buss/dailyprogress'
import selectProjectAndSection from '@/mixins/selectProjectAndSection'
export default {
  name: `daily-progress`,
  mixins: [selectProjectAndSection],
  components: {
    Detail: require(`./hiddenDangerLibrary-store-detail.vue`).default,
    treeEditDialog: require(`./hiddenDangerLibrary-manage.vue`).default,
  },
  data() {
    return {
      filterText: '',
      leftList: [],
      defaultTreeKey: [],
      defaultProps: {
        children: 'childList',
        label: 'name',
      },
      listLoading: false,
      title: '隐患库',
      chooseTreeData: {},
      permission: {
        add: ['100', '1009154:add'],
        show: ['100', '1009154:show'],
        edit: ['100', '1009154:edit'],
        del: ['100', '1009154:del'],
      },
      accidentPotentialArr: [
        { "id": "1", "name": "一般" },
        { "id": "2", "name": "重大" },
      ],
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      hasAdd: false, //是否有新增权限
      loading: false,
      //  当前查看的文件列表
      nowFileList: [],
      showFileDialog: false,
      // list: [{}, {}, {}, {}],
      list: [],
      // 搜索参数
      search: {
        subcontractName: '',
        //pageIndex: 0,
        pageNo: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        contractId: '',
        searchType: '', // 合同类型
        searchName: '', // 合同名称
        company: { children: [] },
        companyId: '',
        project: { children: [] },
        sectionId: '',
        projectId: '',
      },

      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      // 向详情子组件的传值
      treeEditDialogData: {
        show: false,
        nowTreeData: []
      },
      allowSelContract: false,
      //  选择的工程类合同-施工
      contractId: [],
      contract: null,
      // el的table列表
      companyTree: [],
      projectTree: [],
      sectionTree: [],
      name: null,
    }
  },
  filters: {
    numFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ""
      }
    },
    numFilter2(value) {
      try {
        let before = value.toFixed(2)
        return before
      } catch (e) {
        return ""
      }
    },
    numMillionFilter(value) {
      try {
        value = Number.parseFloat(value) / 10000
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ""
      }
    }
  },

  mounted() {
    this.initData()
  },
  watch: {
    filterText(val) {
      this.$refs.treeData.filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    deleteList() {
      let selectionArr = this.$refs['multipleTable'].selection
      if (selectionArr.length > 0) {
        this.$confirm('确定是否删除？', '提示', {
          confirmButtonClass: 'iconfont icon-icon_ok',
          cancelButtonClass: 'iconfont icon-icon_cancel',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        })
          .then(() => {
            this.sealDealHttp(
              `/buss/hiddendangeritems/del`, ``,
              { ids: selectionArr.map(item => item.id) },
              () => {
                this.$messageSuccess('删除成功!')
              })
          })
      } else {
        this.$messageError('请先选择要删除的记录！')
      }
    },

    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.code === 200) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },



    showTreeEditDialog() {
      this.treeEditDialogData = {
        nowTreeData: this.leftList,
        search: this.search,
        show: true
      }
    },

    getLeftTreeNew() {
      let postData = {
        projectId: this.search.projectId,
      }
      this.$httpPost(`buss/hiddendangercategorymanage/getAllByProjectId`, postData).then(res => {
        this.$set(this, 'leftList', res.data)
        if (this.leftList.length > 0) {
          //默认展开的节点
          this.$nextTick(() => {
            let lastLeaf = null
            lastLeaf = this.$publicJs.getDeepSon(this.leftList, 'childList')
            console.log(lastLeaf, 'lastLeaflastLeaflastLeaflastLeaflastLeaflastLeaf')
            this.defaultTreeKey = []
            this.defaultTreeKey.push(lastLeaf.id)
            this.$refs['treeData'].setCurrentKey(lastLeaf.id);
            this.$set(this, 'chooseTreeData', lastLeaf)
            this.$nextTick(() => {
              const node = this.$refs['treeData'].getNode(lastLeaf.id)
              const level = this.getNodeLevelArray(node)
              const name = level.map(node => node.data.name).filter(item => Boolean(item)).join('/')
              this.name = name;
            })

            this.getList(true)
          })
        } else {
          this.list = []
          this.listLoading = true;
          this.$httpPost(`buss/hiddendangercategorymanage/initializeData?projectId=${this.search.projectId}`, postData).then(res => {
            console.log(res)
            if (res.code == 200) {
              this.getLeftTreeNew();
            }
            this.listLoading = false
          }).catch(res => {
            this.listLoading = false
            console.log(res)
          }).finally(() => {
            this.listLoading = false
          })
        }



      }).catch(res => {
        console.log(res)
      })
    },
    handleNodeClick(data, node) {
      console.log(data)
      this.$set(this, 'chooseTreeData', data)
      const level = this.getNodeLevelArray(node)
      const name = level.map(node => node.data.name).filter(item => Boolean(item)).join('/')
      this.name = name;
      if (this.chooseTreeData.id) {
        this.getList(true)
      }
    },
    getNodeLevelArray(node, level = []) {
      level.unshift(node)
      if (node.parent) {
        this.getNodeLevelArray(node.parent, level)
      }
      return level
    },
    submitImportExcel(file) {
      let fd = new FormData()
      fd.append('file', file)
      fd.append("projectId", this.search.projectId)
      fd.append("sectionId", this.search.sectionId)
      fd.append('specialtyType', this.search.specialtyType)
      fd.append('Content-Type', 'multipart/form-data; boundary=----WebKitFormBoundaryIOi8qEBAFV1KN25n')
      this.$httpPost(`buss/basicsBasicsHiddenDangerCategoryManage/importBasicsHiddenDangerCategoryManageList`, fd).then(res => {
        if (res.code == 200) {
          console.log(`成功导入数据`)
          this.$messageSuccess("成功导入数据")
          this.getLeftTreeNew();
        } else {
          this.$messageError("请求导入excel失败:" + res.msg)
          console.log("请求导入excel失败:" + res.msg)
        }
      }).catch(e => {
        console.log(e);
      })
    },
    //模板下载
    templateDownload() {
      this.$httpPost(`/buss/imageProgressBreak/downfile`,
        this.search, { responseType: 'blob' }).then(res => {
          doCreateObject(res, '形象工程分解.xlsx');
        }).catch(e => {
          console.log(e);
          this.$messageError("请求excel模板失败")
        })
    },
    initData() {
      this.companyTree = []

      projectSectionInfo.getLeftProjectTree().then(res => {
        if (res.code === 200) {
          if (res.data.length > 0) {
            this.projectTree = res.data
            if (this.changeHeaderProject == '') {
              this.search.projectId = this.projectTree[0].id;
            } else {
              this.$set(this.search, 'projectId', this.changeHeaderProject)
            }
            this.getSectionByProjectId();
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取项目标段树失败")
      })


    },

    getProjectByCompanyId() {
      if (this.search.projectId) {
        this.search.projectId = ''
      }
      this.companyTree.forEach((item) => {
        if (item.id === this.search.buildCompanyId) {
          this.projectTree = item.children
          if (this.projectTree.length > 0) {
            this.search.projectId = this.projectTree[0].id;
            this.getSectionByProjectId();
            // this.getLeftTree()
          }
        }
      })
    },

    /**
     * 根据项目id获取标段列表
     * getContractByProjectId
     * */
    getSectionByProjectId() {
      if (this.search.sectionId) {
        this.search.sectionId = ''
      }
      console.log(11111);
      console.log(this.search.projectId, 'this.search.projectId');
      if (this.search.projectId) {
        this.projectTree.forEach((item) => {
          if (item.id === this.search.projectId) {
            this.sectionTree = item.children
            if (this.sectionTree.length > 0) {
              this.search.sectionId = this.sectionTree[0].id
              this.getLeftTreeNew();
              // this.getList()
            }
          }
        })
      }
    },



    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },


    // 点击单元格
    cellClick(row, column, cell, event) {
      if (column.property === 'checkContent') {
        this.showDialog('edit', '查看修改', row.id)
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageIndex = 0
      }
      console.log(this.chooseTreeData)
      this.list = []
      let param = {
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        hiddenDangerCategoryId: this.chooseTreeData.id,
        checkContent: this.search.checkContent
      }

      this.$httpPost(`buss/hiddendangeritems/listPage`, param).then(res => {
        if (res.code == 200) {
          /*if(res.list.length>0){
            this.list.forEach((item,index)=>{
              console.log(item)
            })
          }*/
          this.list = res.data.content
          this.search.total = res.data.totalElements
        } else {
          msgUtil.error2(res.data.message)
        }
      })

    },

    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },



    /*  操作 */
    showDialog(type, typeName, detailId) {
      console.log(this.chooseTreeData);
      if (!this.chooseTreeData) {
        this.$messageError("请先选中要加的叶子节点")
        return;
      }

      if (!this.chooseTreeData.parentCode || this.chooseTreeData.childList.length > 0) {
        this.$messageError("只有叶子节点允许新增工程明细")
        return;
      }


      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
            chooseTreeData: this.chooseTreeData,
            name: this.name
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            chooseTreeData: this.chooseTreeData,
            name: this.name
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            dailyprogress.del(param).then(res => {
              if (res.status === 1) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break

      }
    },




  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.list_wrap {
  margin-top: 20px;
}
.left-box {
  min-width: 200px;
  border-right: 1px #e2e8ec solid;
  padding-bottom: 50px;
  position: relative;
  .left-tree-box {
    margin-top: 15px;
    max-height: calc(100vh - 300px);
    overflow: auto;
  }
  .bottom-button {
    width: 110px;
    position: absolute;
    bottom: 0;
    left: calc(50% - 55px);
  }
  p {
    cursor: pointer;
    font-size: 14px;
  }
}
.right-box {
  width: calc(100% - 200px);
  padding-left: 15px;
}
</style>
